<template>
  <div class="app-container" ref="content">
    <div style="text-align: center;padding: 10px">《模拟演练{{DrillInfo.name}}》-详情信息</div>
    <el-row :gutter="10">
      <el-col :span="12" :offset="6">
        <el-form :model="DrillInfo" ref="DrillInfo" label-width="100px">
          <el-form-item label="演练名称:" prop="name">
            {{ DrillInfo.name }}
          </el-form-item>
          <el-form-item label="所属主体:" prop="enterpriseName">
            {{ DrillInfo.enterpriseName }}
          </el-form-item>
          <el-form-item label="预警名称:" prop="fireAlarmName">
            {{ DrillInfo.fireAlarmName }}
          </el-form-item>
          <el-form-item label="所属建筑" prop="buildName">
            {{ DrillInfo.buildName }}
          </el-form-item>
          <el-form-item label="详情地址:" prop="loaction">
            {{ DrillInfo.loaction  }}
          </el-form-item>
          <el-form-item label="确定时间:" prop="fireConfirmTime">
            {{ DrillInfo.fireConfirmTime  |dateFormat}}
          </el-form-item>
          <el-form-item label="用户名称:" prop="userName">
            {{ DrillInfo.userName }}
            <el-button type="primary" icon="el-icon-edit" class="filter-item" style="margin-left: 10px" @click="realTimeVideo()">发起视频</el-button>
          </el-form-item>
          <el-form-item label="起火描述:" prop="fireDescription">
            {{ DrillInfo.fireDescription }}
          </el-form-item>
          <el-form-item label="救援时间:" prop="rescueTime">
            {{ DrillInfo.rescueTime | dateFormat}}
          </el-form-item>
          <el-form-item label="结束时间:" prop="endTime">
            {{ DrillInfo.endTime | dateFormat}}
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-dialog title="视频展示区域" :visible.sync="videoDialogVisible" width="50%" style="height: 100vh">
      <div style="position: relative;max-height: 446px">
        <video ref="localVideo" playsinline autoplay width="30%" style="position: absolute;top: 0;left: 0;"></video>
        <video ref="remoteVideo" playsinline autoplay width="100%"  style="height: 340px"></video>
      </div>
      <div style="text-align: center;margin-top: 10px">
        <el-button type="danger" @click="hungUp">挂断</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getInFireInfoVo} from "@/api/fireInfo";
import 'aliyun-webrtc-sdk'
import {launchFireVideo, deleteChannel} from "@/api/alirtc";


export default {
  name: "DrillInfo",
  data(){
    return{
      DrillInfo:{

      },
      videoDialogVisible:false,
      deleteForm:{
        action:"DeleteChannel",
        channelId:'',
      },
    }
  },
  created() {
    this.$nextTick(() => {
      this.aliWebrtc = new AliRtcEngine();
      this.isSupport(this.aliWebrtc,true)
      this.getInFireInfoVo(this.$route.params.ucId)
    });
  },
  methods:{
      getInFireInfoVo(val){
          //获取火情信息数据
          let loadingInstance = this.$loading({
              target:this.$refs.content,
              text:'数据加载中'
          });
          getInFireInfoVo({ucId:val}).then(res=>{
              this.fireInfoInfo = res.data
              loadingInstance.close()
              this.$notify.success({
                  title: '成功',
                  message: "获取火情信息成功"
              })
          }).catch(error=>{
              loadingInstance.close()
              this.$notify.error({
                  title: '失败',
                  message: "获取火情信息失败"
              })
          })
      },
      hungUp(){
          this.leaveVideo(true)
      },
      //校验当前设备是否支持
      isSupport(val,debug){
          let option = {}
          if (debug){
              option.isDebug=true
          }
          val.isSupport(option).then((res)=>{
              this.onJoinEvent(val)
              this.onPublisher(val)
              this.onBye(this.aliWebrtc)
              this.onLeave(val)
              this.OnRefresh(val)
          }).catch((error)=>{
              console.log("不支持webrtc",error.message)
          })
      },
      //页面刷新时调用
      OnRefresh(val){
          window.onbeforeunload=function (e) {
              if (!val){
                  console.log("isSupport失败");
                  return ;
              }
              val.leaveChannel();
              val.dispose();
          }
      },
      //本地预览
      startPreview(val){
          this.aliWebrtc.startPreview(this.$refs.localVideo).then(()=>{
              console.log("本地预览")
          }).catch((error) => {
              console.log("预览失败",error)
          });
      },
      //推发布流
      publish(val){
          val.configLocalAudioPublish = true;
          val.configLocalCameraPublish = true;
          val.publish().then(()=>{
              console.log("发布流成功")
          } ,(error)=>{
              console.log("发布流失败",error.message);
          });
      },

      // remote用户加入房间 onJoin
      onJoinEvent(val){
          val.on("onJoin", (publisher) => {
              console.log(publisher)
              if(publisher.userId){
                  console.log(publisher.userId)
              }
              //重置订阅状态
              //默认订阅远端音频和视频大流，但需要调用subscribe才能生效
              //这里取消默认订阅，根据需求进行订阅
              val.configRemoteAudio(publisher.userId, true);
              val.configRemoteCameraTrack(publisher.userId, true, true);
              // showAlert(publisher.displayName + "加入房间","success");
              console.log(publisher.displayName + "加入房间");
          });
      },
      //remote流发布事件 onPublish
      onPublisher(val){
          val.on("onPublisher", (publisher) => {
              val.subscribe(publisher.userId).then((userId)=>{
                  this.$nextTick(() => {
                      val.setDisplayRemoteVideo(userId,this.$refs.remoteVideo,1)
                  });
              },(error)=>{
                  console.log(error.message);
              });
          });
      },
      //remote流结束发布事件 onUnPublisher
      onUnPublisher(val){
          val.on("onUnPublisher", (publisher) => {
              console.log("onUnPublisher",publisher);
          });
      },
      // 被服务器踢出或者频道关闭时回调 onBye
      onBye(val){
          val.on("onBye",(message) =>{
              //1:被服务器踢出
              //2:频道关闭
              //3:同一个ID在其他端登录,被服务器踢出
              var msg;
              switch (message.code) {
                  case 1:
                      msg = "被服务器踢出";
                      break;
                  case 2:
                      msg = "频道关闭";
                      break;
                  case 3:
                      msg = "同一个ID在其他端登录,被服务器踢出";
                      break;
                  default:
                      msg = "onBye";
              }
              this.$notify.success({
                  title: '视频挂断',
                  message: msg
              })
              this.leaveVideo(false)
          });
      },
      leaveVideo(val){
          this.aliWebrtc.stopPreview();
          this.aliWebrtc.leaveChannel();
          this.aliWebrtc.dispose();
          this.videoDialogVisible = false
          if (val){
              deleteChannel({channelId:this.channelId}).then(res=>{

              })
          }
      },
      /**
       * 检测到用户离开频道
       * 更新用户列表
       * 移除用户视图
       */
      onLeave(val){
          val.on("onLeave", (publisher) => {
              console.log(publisher);
              this.leaveVideo(true)
          })
      },
      launchFireVideo(){
          //发起实时视频功能
          //展示弹窗区信息
          let _this = this
          launchFireVideo({fireUserId:_this.fireInfoInfo.fireUserId}).then(res=>{
              _this.channelId = res.data.channel
              this.aliWebrtc = new AliRtcEngine();
              this.isSupport(this.aliWebrtc,true)
              this.videoDialogVisible = true
              _this.$nextTick(() => {
                  _this.startPreview(_this.aliWebrtc)
                  _this.aliWebrtc.joinChannel(res.data,_this.fireInfoInfo.userName).then(obj=>{
                      _this.publish(_this.aliWebrtc)
                      console.log("加入频道成功")
                  }).catch((error)=>{
                      console.log("加入频道失败",error)
                  })
              });
          }).catch(error=>{
              this.$notify.error({
                  title: '加入频道失败',
                  message: error.msg
              })
          })
      },
  }

}
</script>
